using MultiAgentsClient.ChatDataStructures;
using MultiAgentsShared;
using static MultiAgentsClient.Manager.WorkflowManager;
using static MultiAgentsClient.Manager.WorkflowWebviewOperator;

namespace MultiAgentsClient.Presentation;

public partial record WorkflowListModel
{
    private readonly IEventBus eventBus;

    public IListState<WorkflowDisp> WorkflowsDisp => ListState<WorkflowDisp>.Empty(this);

    public record ShareWorkflowClickCommand();

    public WorkflowListModel()
    {
        eventBus = EventBus.Instance;

        eventBus.Subscribe<CreateNewWorkflowCompleteCommand>(async cmd => { await CreateNewWorkflowCompleteCommandHandler(cmd); });
        eventBus.Subscribe<UpdateWorkflowCompleteCommand>(async cmd => { await UpdateWorkflowCompleteCommandHandler(cmd); });
        eventBus.Subscribe<GetAllWorkflowCompleteCommand>(async cmd => { await GetAllWorkflowResponseHandler(cmd); });
        eventBus.Subscribe<RemoveWorkflowCompleteCommand>(async cmd => { await RemoveWorkflowResponseHandler(cmd); });
    }

    public void AddWorkflowByShareCode()
    {
        eventBus.Publish(new ShareWorkflowClickCommand());
    }

    public void RemoveWorkflow(int workflowId)
    {
        eventBus.Publish(new RemoveWorkflowCommand(workflowId));
    }

    public void ShareWorkflow(int workflowId)
    {
        eventBus.Publish(new ShareWorkflowCommand(workflowId));
    }

    public void LoadWorkflow(int workflowId)
    {
        eventBus.Publish(new LoadWorkflowCommand(workflowId));
    }

    public void AddWorkflow()
    {
        eventBus.Publish(new CreateNewWorkflowCommand());
    }

    #region commands
    private async Task CreateNewWorkflowCompleteCommandHandler(CreateNewWorkflowCompleteCommand cmd)
    {
        await WorkflowsDisp.AddAsync(cmd.WorkflowConfigDisp);
    }

    private async Task UpdateWorkflowCompleteCommandHandler(UpdateWorkflowCompleteCommand cmd)
    {
        await WorkflowsDisp.UpdateAsync(
            match: cp => cp.Id == cmd.WorkflowConfigDisp.Id,
            updater: cp => cmd.WorkflowConfigDisp,
            default
        );
    }

    private async Task GetAllWorkflowResponseHandler(GetAllWorkflowCompleteCommand cmd)
    {
        await WorkflowsDisp.RemoveAllAsync(item => true, default);
        foreach (WorkflowDisp wfDisp in cmd.WorkflowDisps)
        {
            await WorkflowsDisp.AddAsync(wfDisp);
        }
    }

    private async Task RemoveWorkflowResponseHandler(RemoveWorkflowCompleteCommand cmd)
    {
        await WorkflowsDisp.RemoveAllAsync(item => item.Id == cmd.Workflow, default);
    }
    #endregion
}
